#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>  // 必须包含，用于 WIFEXITED/WEXITSTATUS

#define COMMAND_VALUESIZE 100

int usbhost_auto_test()
{
    int ret = 0;
    int status = system("/userfs/usbhost_test.sh");
    if (status == -1) {
        printf("system cmd run error...\n");
        ret = -1;
    } else {
        printf("exit status value = [0x%x]\n", status);
        if (WIFEXITED(status)) {
            int exit_code = WEXITSTATUS(status);
            if (exit_code == 0) {
                printf("run shell script successfully.\n");
                ret = 0;
            } else {
                printf("run shell script fail, script exit code: %d\n", exit_code);
                ret = exit_code;
            }
        } else {
            printf("script terminated abnormally.\n");
            ret = -1;
        }
    }

    if (ret != 0)
        printf("usbhost test failed. ret = %d\n", ret);

    return ret;
}

int main(int argc, char *argv[])
{
    int test_flag = 0;
    char buf[COMMAND_VALUESIZE] = "usbhost_test";

    printf("usbhost test 开始...\n");

    test_flag = usbhost_auto_test();
    if (test_flag == 0) {
        printf("usbhost 测试成功\n");
        system("echo \"$(date)：usbhost 测试成功\" >> /userfs/all.txt");
    } else if (test_flag == 1) {
        printf("usbhost 挂载失败...\n");
        system("echo \"$(date)：usbhost 挂载失败\" >> /userfs/all.txt");
    } else if (test_flag == 2) {
        printf("usbhost 超时失败...\n");
        system("echo \"$(date)：usbhost 超时失败\" >> /userfs/all.txt");
    }

    if (test_flag == 0) {
        int fd = open("/run/usbhost_capacity", O_RDONLY);
        if (fd < 0) {
            printf("Failed to open /run/usbhost_capacity: %s\n", strerror(errno));
        } else {
            char usbhost_size_str[32] = {0};
            ssize_t r_len = read(fd, usbhost_size_str, sizeof(usbhost_size_str) - 1);
            close(fd);
            if (r_len > 0) {
                usbhost_size_str[r_len] = '\0';
                double cap_kb = strtod(usbhost_size_str, NULL);
                double cap_gb = cap_kb / 1024.0 / 1024.0; // KB → GB

                char cap_buf[64];
                snprintf(cap_buf, sizeof(cap_buf), "capacity:%.4fG ", cap_gb);
                strncat(buf, ": ", sizeof(buf) - strlen(buf) - 1);
                strncat(buf, cap_buf, sizeof(buf) - strlen(buf) - 1);
                printf("Final buf: %s\n", buf);
            }
        }
    }

    return 0;
}